import time
import random
import string
import time
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

from web.forms.project import ProjectModelForm
from web import models

# 导入cos模块创建桶和删除桶
# 注意：实际使用时需要确保此模块存在且配置正确
from utils.tencent.cos import create_cos_bucket, delete_cos_bucket

from django.contrib.auth.decorators import login_required

def dropdown_test(request):
    # 检查用户项目数量
    project_count = request.user.projectuser_set.all().count() if request.user.is_authenticated else 0
    return render(request, 'dropdown_test.html', {'project_count': project_count})

def project_list(request):
    if not request.user.is_authenticated:
        return redirect('login')

    # 获取筛选参数
    search_query = request.GET.get('search', '')
    star_filter = request.GET.get('star', '')
    sort_by = request.GET.get('sort', 'create_datetime')
    sort_order = request.GET.get('order', 'desc')

    # 基本查询 - 获取我参与的所有项目（包括自己创建的）
    all_participated_projects = models.Project.objects.filter(
        projectuser__user=request.user
    )

    # 应用搜索筛选
    if search_query:
        all_participated_projects = all_participated_projects.filter(
            name__icontains=search_query
        )

    # 应用星标筛选
    if star_filter == 'starred':
        all_participated_projects = all_participated_projects.filter(
            projectuser__user=request.user, 
            projectuser__star=True
        )
    elif star_filter == 'unstarred':
        all_participated_projects = all_participated_projects.filter(
            projectuser__user=request.user, 
            projectuser__star=False
        )

    # 应用排序
    sort_field = sort_by
    if sort_order == 'desc':
        sort_field = f'-{sort_by}'

    all_participated_projects = all_participated_projects.order_by(sort_field)

    # 分类项目
    my_created_projects = all_participated_projects.filter(
        creator=request.user
    )

    my_participated_projects = all_participated_projects.exclude(
        creator=request.user
    )

    starred_projects = all_participated_projects.filter(
        projectuser__user=request.user, 
        projectuser__star=True
    )

    # 准备筛选和排序参数，用于模板中的表单
    filter_params = {
        'search_query': search_query,
        'star_filter': star_filter,
        'sort_by': sort_by,
        'sort_order': sort_order
    }

    return render(request, 'project_list.html', {
        'starred_projects': starred_projects,
        'my_created_projects': my_created_projects,
        'my_participated_projects': my_participated_projects,
        'filter_params': filter_params
    })


@login_required
def project_detail(request, project_id):
    try:
        project = models.Project.objects.get(id=project_id)
        return render(request, 'project_detail.html', {'project': project})
    except models.Project.DoesNotExist:
        return HttpResponse('项目不存在')


@login_required
def project_add(request):
    if request.method == 'GET':
        form = ProjectModelForm()
        return render(request, 'project_add.html', {'form': form})
    form = ProjectModelForm(data=request.POST)
    if form.is_valid():
        # 创建项目前的准备工作
        # 1. 生成唯一的桶名称
        bucket_name = f"{request.user.username}-{''.join(random.choices(string.ascii_lowercase + string.digits, k=6))}-{int(time.time())}"
        # 2. 选择桶区域（这里使用默认区域，实际可根据需求修改）
        region = 'ap-guangzhou'
        
        # 3. 创建cos桶
        try:
            create_cos_bucket(bucket_name, region)
            print(f'成功创建COS桶: {bucket_name}')
        except Exception as e:
            print(f'创建COS桶失败: {str(e)}')
            # 在实际项目中，可能需要添加日志记录或回滚操作
            # 这里简单地继续执行，将有问题的桶名称仍然保存到数据库
            # 后续可以通过其他方式处理失败的桶创建

        
        # 4. 填充模型中未在表单中定义的字段
        project_obj = form.save(commit=False)
        project_obj.creator = request.user
        project_obj.bucket = bucket_name
        project_obj.region = region
        
        # 5. 保存项目
        project_obj.save()
        
        # 添加日志，确认项目已创建
        print(f'成功创建项目: {project_obj.name}, ID: {project_obj.id}')
        
        # 检查并确保项目创建者被添加为项目参与者
        try:
            project_user = models.ProjectUser.objects.get(project=project_obj, user=request.user)
            # 更新星标状态
            if project_user.star != project_obj.star:
                project_user.star = project_obj.star
                project_user.save()
                print(f'已更新项目参与者星标状态: 用户 {request.user.username} 项目 {project_obj.name}')
            else:
                print(f'项目参与者记录已存在: 用户 {request.user.username} 已添加到项目 {project_obj.name}')
        except models.ProjectUser.DoesNotExist:
            # 如果不存在，创建项目参与者记录，并设置星标状态
            models.ProjectUser.objects.create(project=project_obj, user=request.user, star=project_obj.star)
            print(f'已创建项目参与者记录: 用户 {request.user.username} 已添加到项目 {project_obj.name}，星标状态: {project_obj.star}')
        
        return redirect('project_list')
    return render(request, 'project_add.html', {'form': form})


@login_required
def project_delete(request, project_id):
    print(f'接收到删除项目请求，项目ID: {project_id}')
    print(f'请求用户: {request.user.username}')
    try:
        project = models.Project.objects.get(id=project_id)
        print(f'找到项目: {project.name}')
        
        # 检查用户是否是项目创建者
        if project.creator != request.user:
            print(f'用户 {request.user.username} 不是项目 {project.name} 的创建者')
            return JsonResponse({'status': False, 'msg': '只有项目创建者才能删除项目'})
        
        # 尝试删除COS桶
        try:
            delete_cos_bucket(project.bucket, project.region)
            print(f'成功删除COS桶: {project.bucket}')
        except Exception as e:
            print(f'删除COS桶失败: {str(e)}')
            # 即使删除桶失败，仍然继续删除数据库中的项目记录
            # 后续可以通过其他方式处理失败的桶删除
        
        # 删除项目记录
        project.delete()
        print(f'成功删除项目: {project.name}')
        
        return JsonResponse({'status': True, 'msg': '项目删除成功'})
    except models.Project.DoesNotExist:
        print(f'项目ID {project_id} 不存在')
        return JsonResponse({'status': False, 'msg': '项目不存在'})
